import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
  RouteRecordStringComponent
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';

import { message } from 'ant-design-vue';

import { getAllMenusApi } from '#/api';
import { BasicLayout, IFrameView } from '#/layouts';
import { $t } from '#/locales';

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };

  console.log('generateAccess 被调用，当前访问模式:', preferences.app.accessMode);
  console.log('默认主页设置为:', preferences.app.defaultHomePath);
  
  // 确保至少有一个默认路由可用，防止404错误
  const defaultRoutes: RouteRecordStringComponent[] = [
    {
      meta: {
        icon: 'lucide:layout-dashboard',
        order: -1,
        title: '仪表盘',
      },
      name: 'Dashboard',
      path: '/dashboard',
      component: 'LAYOUT',
      children: [
        {
          name: 'Analytics',
          path: '/dashboard/analytics',
          component: '/dashboard/analytics/index',
          meta: {
            affixTab: true,
            icon: 'lucide:area-chart',
            title: '分析页',
          },
        },
        {
          name: 'Workspace',
          path: '/dashboard/workspace',
          component: '/dashboard/workspace/index',
          meta: {
            icon: 'carbon:workspace',
            title: '工作台',
          },
        },
      ],
    },
  ];
  
  // 尝试使用后端模式获取菜单，如果失败则使用默认路由
  return await generateAccessible('backend', {
    ...options,
    fetchMenuListAsync: async () => {
      console.log('fetchMenuListAsync 被调用，准备获取菜单数据');
      message.loading({
        content: `${$t('common.loadingMenu')}...`,
        duration: 1.5,
      });
      
      console.log('调用 getAllMenusApi() 获取菜单数据');
      try {
        const menus = await getAllMenusApi();
        console.log('getAllMenusApi() 返回的菜单数据:', menus);
        
        // 如果后端返回了有效的菜单数据，则使用它
        if (menus && Array.isArray(menus) && menus.length > 0) {
          console.log('使用后端返回的菜单数据');
          return menus;
        }
        
        // 否则使用默认路由
        console.warn('后端未返回有效的菜单数据，使用默认路由');
        return defaultRoutes;
      } catch (error) {
        console.error('获取菜单数据失败:', error);
        message.error('获取菜单数据失败，使用默认路由');
        return defaultRoutes;
      }
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
